from rest_framework import serializers
from django_redis import get_redis_connection

from oauth.models import OAuthQQUser
from oauth.utils import check_access_token
from users.models import User


class OauthQQUserSerializer(serializers.Serializer):
    """
    对数据进行校验（手机号，密码，短信验证码，Openid(处理过的)）
        1.短信验证码
        2.openid(处理过的)
        3.根据手机号查询用户信息，判断是否存在

    """
    access_token = serializers.CharField(label='操作凭证')
    #邮政编码，身份证号码，邮箱，营业执照
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate(self, attrs):
        #1.短信验证码
        #1.1用户提交的
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        #1.2redis中的
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s'%mobile)
        if redis_conn is None:
            return serializers.ValidationError('短信验证码已过期')

        #1.3对比
        if redis_code.decode() != sms_code:
            return serializers.ValidationError('短信验证码不一致')

        #2.openid(处理过得)
        access_token = attrs.get('access_token')
        openid = check_access_token(access_token)
        if openid is None:
            return serializers.ValidationError('token被篡改')

        attrs['openid']=openid

        #3.根据手机号判断用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except:


            #如果用户不存在就创建用户
            #创建用户先不
            pass

        else:
             #如果用户存在就校验密码
            if not user.check_password(attrs['password']):
                return serializers.ValidationError('密码不一致')

            attrs['user']=user

        return attrs

    #data -- > attrs  --> valdated_data

    def create(self, validated_data):

        user = validated_data.get('user')
        openid = validated_data.get('openid')

        if user is None:
            #创建用户
            user = User.objects.create(

                username = validated_data.get('mobile'),
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password')
            )
            user.set_password(validated_data.get('password'))
            user.save()

        qquser = OAuthQQUser.objects.create(
            user = user,
            openid = openid
        )

        return qquser

















